package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义权限不足的类，但是本项目并不涉及到权限的问题，所以就是一个测试
 */
@Service
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //控制台打印一下
        log.debug("权限不足");
        //设置响应的内容
        //1.设置状态码 403 权限不足
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //2.设置响应内容的类型
        response.setContentType("application/json;charset=UTF-8");
        //3.设置响应内容
        JsonResult jsonResult = new JsonResult(StatusCode.NOT_LOGIN);
        String jsonString = JSON.toJSONString(jsonResult);
        //获取输出流
        PrintWriter writer = response.getWriter();
        //通过输出流，写出响应
        writer.write(jsonString);
        //冲刷输出流
        writer.flush();
        //关闭输出流
        writer.close();
    }
}
